package day11;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

//测试Lock：模拟购票
//模拟火车站售票窗口，要求：票池共100张票，3个售票窗口同时卖票
//,售票过程需显示"窗口X卖出第Y张票",使用Lock保证票数正确
//当票卖完时所有线程终止
public class TestLock {
    int sum = 100;//表示票的总数
    int n = 0;
    //用来定义lock锁对象
    ReentrantLock lock = new ReentrantLock();

    public void buy() {//每个窗口，买一次票的过程
        String name = Thread.currentThread().getName();
        //lock.lock();//手动加锁   获取不到，会一直等待
        //lock.tryLock()，尝试获取锁(手动加锁，返回true，返回false)
        //lock.trylock(时间,单位),单位时间过后没有获取到锁就不等待了
        try {
            if (lock.tryLock(3, TimeUnit.SECONDS)) {//尝试获取锁
                try {
                    if (sum > 0) {
                        sum--;
                        n++;
                        Thread.sleep(100);
                        System.out.println(name + "成功售出第" + n + "张票,剩余" + sum + "票");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {//一般类似于关闭IO流，无论是否发生异常都要执行
                    lock.unlock();//手动释放锁
                }
            }else {
                System.out.println(name+"没有获取到锁");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        TestLock tl = new TestLock();
        for (int i = 1; i <= 3; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    tl.buy();
                    if (tl.sum==0)break;
                }
            }, "窗口" + i).start();
        }
    }
}
